package com.bbf.tio.server;

import com.bbf.tio.common.AbstractTioHandler;
import com.bbf.tio.common.TioConstants;
import com.bbf.tio.common.TioPacket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.Aio;
import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;
import org.tio.server.intf.ServerAioHandler;

/**
 * 消息处理类
 * @author BBF
 */
public class TioServerAioHandler extends AbstractTioHandler
    implements ServerAioHandler {
  private static final Logger LOGGER = LoggerFactory.getLogger(TioServerAioHandler.class);

  /**
   * 处理消息
   */
  @Override
  public void handler(Packet packet,
                      ChannelContext channelContext) {
    TioPacket tioPacket = (TioPacket) packet;
    byte[] body = tioPacket.getBody();
    if (body != null) {
      String str = new String(body, TioConstants.CHARSET_UTF8);
      LOGGER.info("[TioServerAioHandler.handler]收到消息：--{}--", str);
      TioPacket respPacket = new TioPacket();
      String msg = "--服务器回复：接受到的消息是--" + str + "--";
      respPacket.setBody(msg.getBytes(TioConstants.CHARSET_UTF8));
      Aio.send(channelContext, respPacket);
    }
  }

  @Override
  public void showPacket(TioPacket packet) {
    LOGGER.info("[TioServerAioHandler.showPacket]接收数据：{}", packet.toString());
  }
}
